package com.nulldev.util.uri.yt;

import java.net.URL;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.regex.Pattern;

import com.nulldev.util.java.DataSet;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.math.MathUtil;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.URIUtil2;

@Deprecated
/**
 * Replaced with YouTubeSearch, providing more information.
 * @author null
 */
public class YTSearch {
	
	static {
		LoggerFactory.getLogger().error("YTSearch is marked for removal, use YouTubeSearch instead.");
	}

    private String links[];
    private String extra[];
    private String titles[];
    
    private int prevVists = 1;
    
    /**
     * Replaced with YouTubeSearch, providing more information.
     * @author null
     */
    public YTSearch() {
    }
    
    public LinkedList<DataSet<String, URL>> sendQuery(String query) {
    	final LinkedList<DataSet<String, URL>> out = new LinkedList<DataSet<String, URL>>();
    	
        int i, pgno = 1, temp;
        String search_link = "https://www.youtube.com/results?q=";
        //Scanner inp = new Scanner(System.in);
        //Building search_link
        //System.out.print("Enter your search query : ");
        //query=inp.nextLine();
        query = query.trim();
        int len = query.length();
        for (i = 0; i < len; i++) {
            if(query.charAt(i) == ' ') {
                while(query.charAt(i+1) == ' ') {
                    i++;
                }
                search_link = search_link.concat("+");
            }
            else{
                search_link = search_link.concat(String.valueOf(query.charAt(i)));
            }
        }
        
        //println(search_link);
        
        getLinks(search_link);
        
        
        getTitles();
        //printAll();
                
        for (int ix = 5; ix > 0; ix--) {
            //System.out.print("press 1 for previous page\n      2 for next page\n      0 to exit : ");
            //temp=inp.nextInt();
        	temp = 0;
            if (temp == 0) {
                break;
            }else if(temp == 2) {
                pgno++;
                //search_link=search_link+"&page="+pgno;
                getLinks(search_link + "&page=" + pgno);
                getTitles();
            }else if(temp == 1) {                
                if (pgno == 1) {
                    //System.out.println("Page 1 reached. Previous page not possible.");
                	break;
                }else{
                    pgno--;
                    getLinks(search_link + "&page=" + pgno);
                    getTitles();
                }
            }
        } 
        
//      for(i=0;i<extra.length;i++){
//      //System.out.println(links[i]);
//      //System.out.println(titles[i]);
//      try {
//      	System.out.println(titles[i].substring(titles[i].indexOf(" aria-describedby="), (titles[i].indexOf(".")))+"---"+links[i]);
//      }catch (Exception e) {
//      	System.out.println(titles[i] + "---" + links[i]);
//      }
//  }
        for (int xi = 0; xi < extra.length; xi++) {
        	if (xi < titles.length) {
            	final DataSet<String, URL> toAdd = new DataSet<String, URL>(
            			titles[xi],
            			URIUtil.safeCreate(links[xi]));
            	out.add(toAdd);
        	}
        }
        
        prevVists = 0;
        return out;
    }
    
    void getLinks(String pageLink) {
//        URL link = new URL(pageLink);
//        BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));        
        int b,i;
//        String src=null;
//        while((b=in.read()) != -1){
//                src=src+(char)b;
//        }
        if (this.prevVists > 0) {
        	//LoggerFactory.getLogger().info("Waiting a few ms to prevent bot detection...");
        	try {
				Thread.sleep(MathUtil.randInt(900, 2400) * prevVists);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
    	this.prevVists += 1;
    	String src = URIUtil.downloadPageS(URIUtil.safeCreate(pageLink), URIUtil2.RandomUserAgent.getRandomUserAgent());
        /*String src = null;
        int i;
        try {
            File file = new File("C:\\Users\\Akash Thakrar\\Documents\\NetBeansProjects\\YoutubeSearch\\build\\classes\\source.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                    stringBuffer.append("\n");
            }
            fileReader.close();
            src = stringBuffer.toString();
        }
        catch (IOException e) {
                    e.printStackTrace();
        }*/
        extra=src.split("\" data-context-item-id=\"");
        links = new String[extra.length-1];
       // System.out.println(src);
        for(i=1;i<extra.length;i++){
            links[i-1] = "https://www.youtube.com/watch?v="+extra[i].substring(0,11);
            //System.out.println(links[i-1]);
        }
    }
    
    void getTitles() {
        
        ///////////////////////////////////////////
        ////////////////////////////////////////////
        
        String src = null;
        int i;
        /*try {
            File file = new File("C:\\Users\\Akash Thakrar\\Documents\\NetBeansProjects\\YoutubeSearch\\build\\classes\\source.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                    stringBuffer.append("\n");
            }
            fileReader.close();
            src = stringBuffer.toString();
        }
        catch (IOException e) {
                    e.printStackTrace();
        }
        //extra=src.split("\" data-context-item-id=\"");*/
        titles = new String[extra.length-1];
        //////////////////////////////////////
        //////////////////////////////////////
        String[] extra1 = new String[7];
        Scanner in = new Scanner(System.in);
        for(i=1;i<extra.length;i++){
            extra1 = extra[i].split("title=");
            try {
            	titles[i-1] = (extra1[3].substring(1,extra1[3].indexOf("rel")-2).replaceAll(Pattern.quote("aria-describedby=\"description-id-"), "")).split(" Duration: ")[0];
            }catch (Exception e) {
            	try {
            		titles[i-1] = extra1[3].substring(1,extra1[3].indexOf("rel")-2).replaceAll(Pattern.quote("aria-describedby=\"description-id-"), "");
            	}catch (Exception e1) {
            		e1.printStackTrace();
            	}
            }
            //System.out.println(titles[i-1]);
            //in.nextLine();
        }
	}
    
//    public void printAll(){
//        int i;
//        for(i=0;i<extra.length;i++){
//            //System.out.println(links[i]);
//            //System.out.println(titles[i]);
//            try {
//            	System.out.println(titles[i].substring(titles[i].indexOf(" aria-describedby="), (titles[i].indexOf(".")))+"---"+links[i]);
//            }catch (Exception e) {
//            	System.out.println(titles[i] + "---" + links[i]);
//            }
//        }
//    }
}
